package com.mall.product.advice;


import com.mall.common.enums.BizCodeEnum;
import com.mall.common.utils.BaseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  集中处理所有的异常情况
 *
 *
 */
@Slf4j
@RestControllerAdvice(basePackages = {"com.mall"})//  == @ControllerAdvice + @ResponseBody
public class BaseControllerAdvice {


    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public BaseResult handleValidException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题 {}, 异常类型：{}" ,e.getMessage(), e.getClass());
        e.printStackTrace();
        BindingResult bindingResult = e.getBindingResult();

        Map<String,String> errorMap = new HashMap<>();

        List<FieldError> fieldErrors = bindingResult.getFieldErrors();

        fieldErrors.forEach((fieldError) -> {
            // 遍历
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });


        // return BaseResult.error(BizCodeEnum.VALID_EXCEPTION.code(),BizCodeEnum.VALID_EXCEPTION.val()).put("data",errorMap);

        return BaseResult.error(BizCodeEnum.VALID_EXCEPTION).put("data",errorMap);
    }


    @ExceptionHandler(value = Throwable.class)
    public BaseResult  handleException(Throwable throwable){
        log.error("数据校验出现问题 {}, 异常类型：{}" ,throwable.getMessage(), throwable.getClass());
        throwable.printStackTrace();
        return BaseResult.error(BizCodeEnum.UNKNOW_EXCEPTION);
    }


































}
